# -*- coding: utf-8 -*-
"""
创建 WMS 示例数据（仅用于演示）：
- 货位类型：STANDARD（存在则跳过）
- 演示货位：SB-TEST-001（存在则跳过），自动关联任一可用仓库
  若站点没有可用仓库，则仅提示，不报错

用法：
bench --site dev.local execute eam.test.create_wms_sample_data.run
"""
import frappe

BIN_TYPE_NAME = "STANDARD"
BIN_NAME = "SB-TEST-001"

def _ensure_bin_type():
    if not frappe.db.exists("DocType", "Storage Bin Type"):
        print("skip: DocType 'Storage Bin Type' not found")
        return
    if not frappe.db.exists("Storage Bin Type", BIN_TYPE_NAME):
        doc = frappe.new_doc("Storage Bin Type")
        # 尽量设置友好名称字段（不同版本字段可能不同）
        if doc.meta.has_field("storage_bin_type_name"):
            doc.storage_bin_type_name = BIN_TYPE_NAME
        doc.name = BIN_TYPE_NAME
        doc.insert(ignore_permissions=True)
        print("created_bin_type")
    else:
        print("bin_type_exists")

def _pick_any_warehouse():
    if not frappe.db.exists("DocType", "Warehouse"):
        return None
    wh = frappe.get_all("Warehouse", filters={"disabled": 0}, fields=["name"], limit=1)
    return wh[0]["name"] if wh else None

def _ensure_bin():
    if not frappe.db.exists("DocType", "Storage Bin"):
        print("skip: DocType 'Storage Bin' not found")
        return
    if frappe.db.exists("Storage Bin", BIN_NAME):
        print("bin_exists")
        return

    warehouse = _pick_any_warehouse()
    if not warehouse:
        print("no_warehouse_available")
        return

    doc = frappe.new_doc("Storage Bin")
    # 兼容不同版本字段
    if doc.meta.has_field("storage_bin_name"):
        doc.storage_bin_name = BIN_NAME
    doc.name = BIN_NAME
    if doc.meta.has_field("warehouse"):
        doc.warehouse = warehouse
    if doc.meta.has_field("storage_bin_type") and frappe.db.exists("Storage Bin Type", BIN_TYPE_NAME):
        doc.storage_bin_type = BIN_TYPE_NAME
    if doc.meta.has_field("disabled"):
        doc.disabled = 0

    doc.insert(ignore_permissions=True)
    print("created_bin")

def run():
    _ensure_bin_type()
    _ensure_bin()
    frappe.db.commit()
    print("sample_data_ready")